// 导入API工具函数
import {get, put, del} from './api.js';

// 分页状态
let currentPage = 1;
let totalPages = 1;
let currentCourse = '';
let currentMajor = '';
let currentLimit = 5;

// 查询成绩数据
async function queryScores(page = 1) {
    try {
        currentPage = page;
        
        // 获取选择的课程、专业和每页显示条数
        currentCourse = document.getElementById('course').value;
        currentMajor = document.getElementById('major').value;
        currentLimit = parseInt(document.getElementById('page-size').value) || 5;
        
        // 构建查询参数
        const params = new URLSearchParams();
        if (currentCourse) params.append('courseName', currentCourse);
        if (currentMajor) params.append('major', currentMajor);
        params.append('page', page);
        params.append('limit', currentLimit);
        
        // 如果没有选择任何条件，不进行查询
        if (!currentCourse && !currentMajor) {
            clearTable();
            return;
        }
        
        // 显示加载状态
        const tbody = document.querySelector('#score-table tbody');
        tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">加载中...</td></tr>';
        
        // 发送GET请求
        const response = await get(`/scores/search?${params}`);
        
        if (response.status === 'success') {
            const data = response.data.results;
            totalPages = response.data.pagination.pages;
            
            // 清空表格
            tbody.innerHTML = '';
            
            // 填充成绩数据
            if (data.length > 0) {
                data.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.sid}</td>
                        <td>${item.name}</td>
                        <td><input type="number" value="${item.score || ''}" min="0" max="100" data-sid="${item.sid}" data-cid="${item.cid}"></td>
                        <td>
                            <button class="save-btn" data-sid="${item.sid}" data-cid="${item.cid}" data-name="${item.name}">保存</button>
                            <button class="delete-btn" data-sid="${item.sid}" data-cid="${item.cid}">删除</button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                // 绑定事件
                bindRowEvents();
            } else {
                tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>';
            }
            
            // 更新分页控件
            updatePagination(response.data.pagination);
        } else {
            tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">查询失败: ' + response.message + '</td></tr>';
        }
    } catch (error) {
        console.error('查询出错:', error);
        const tbody = document.querySelector('#score-table tbody');
        tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">查询出错: ' + error.message + '</td></tr>';
    }
}

// 清空表格
function clearTable() {
    const tbody = document.querySelector('#score-table tbody');
    tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">请选择课程或专业进行查询</td></tr>';
}

// 绑定行内事件
function bindRowEvents() {
    // 绑定保存按钮事件
    document.querySelectorAll('.save-btn').forEach(button => {
        button.addEventListener('click', function() {
            const sid = this.getAttribute('data-sid');
            const cid = this.getAttribute('data-cid');
            const name = this.getAttribute('data-name');
            saveScore(sid, cid, name);
        });
    });
    
    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', function() {
            const sid = this.getAttribute('data-sid');
            const cid = this.getAttribute('data-cid');
            deleteScore(sid, cid);
        });
    });
}

// 保存成绩
async function saveScore(sid, cid, name) {
    try {
        // 获取对应的成绩输入框
        const input = document.querySelector(`input[data-sid="${sid}"][data-cid="${cid}"]`);
        const score = input.value;
        
        // 验证成绩
        if (score === '' || score === null) {
            alert('请输入成绩');
            return;
        }
        
        if (isNaN(score) || score < 0 || score > 100) {
            alert('成绩必须是0-100之间的数字');
            return;
        }
        
        // 发送PUT请求更新成绩
        const response = await put(`/scores?sid=${sid}&cid=${cid}&score=${score}`, {});
        
        if (response.status === 'success') {
            alert(`保存成功！\n学号：${sid}\n姓名：${name}\n成绩：${score}`);
        } else {
            alert(`保存失败：${response.message}`);
        }
    } catch (error) {
        console.error('保存出错:', error);
        alert('保存出错: ' + error.message);
    }
}

// 删除成绩
async function deleteScore(sid, cid) {
    try {
        if (confirm(`确定要删除学号为 ${sid} 的记录吗？`)) {
            // 发送DELETE请求删除成绩
            const response = await del(`/scores?sid=${sid}&cid=${cid}`);
            
            if (response.status === 'success') {
                alert(`删除成功！\n学号：${sid}`);
                // 重新查询数据
                queryScores(currentPage);
            } else {
                alert(`删除失败：${response.message}`);
            }
        }
    } catch (error) {
        console.error('删除出错:', error);
        alert('删除出错: ' + error.message);
    }
}

// 更新分页控件
function updatePagination(pagination) {
    const paginationControls = document.getElementById('pagination-controls');
    paginationControls.innerHTML = '';
    
    const { page, pages, total, limit } = pagination;
    
    // 添加页码信息
    const pageInfo = document.createElement('span');
    pageInfo.textContent = `第 ${page} 页，共 ${pages} 页（共 ${total} 条）`;
    paginationControls.appendChild(pageInfo);
    
    // 添加上一页按钮
    if (page > 1) {
        const prevLink = document.createElement('a');
        prevLink.href = '#';
        prevLink.textContent = '上一页';
        prevLink.addEventListener('click', (e) => {
            e.preventDefault();
            queryScores(page - 1);
        });
        paginationControls.appendChild(prevLink);
    }
    
    // 添加页码链接（只显示当前页前后几页）
    const startPage = Math.max(1, page - 2);
    const endPage = Math.min(pages, page + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === page) {
            const currentPageSpan = document.createElement('span');
            currentPageSpan.textContent = i;
            currentPageSpan.style.fontWeight = 'bold';
            paginationControls.appendChild(currentPageSpan);
        } else {
            const pageLink = document.createElement('a');
            pageLink.href = '#';
            pageLink.textContent = i;
            pageLink.addEventListener('click', (e) => {
                e.preventDefault();
                queryScores(i);
            });
            paginationControls.appendChild(pageLink);
        }
    }
    
    // 添加下一页按钮
    if (page < pages) {
        const nextLink = document.createElement('a');
        nextLink.href = '#';
        nextLink.textContent = '下一页';
        nextLink.addEventListener('click', (e) => {
            e.preventDefault();
            queryScores(page + 1);
        });
        paginationControls.appendChild(nextLink);
    }
}

// 绑定事件
function bindEvents() {
    // 查询按钮事件
    const queryButton = document.getElementById('query-btn');
    if (queryButton) {
        queryButton.addEventListener('click', () => queryScores(1));
    }
    
    // 课程选择变化事件
    const courseSelect = document.getElementById('course');
    if (courseSelect) {
        courseSelect.addEventListener('change', () => {
            // 可以在这里添加自动查询功能
            // queryScores(1);
        });
    }
    
    // 专业选择变化事件
    const majorSelect = document.getElementById('major');
    if (majorSelect) {
        majorSelect.addEventListener('change', () => {
            // 可以在这里添加自动查询功能
            // queryScores(1);
        });
    }

    // 每页显示条数变化事件
    const pageSizeSelect = document.getElementById('page-size');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', () => {
            queryScores(1); // 重新查询第一页
        });
    }
}

// 页面加载完成后绑定事件
document.addEventListener('DOMContentLoaded', () => {
    bindEvents();
    clearTable();
});

export { queryScores };